﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using Telerik.Windows.Controls;
using Broker.View.PersonView;
using Broker.View.ProductView;
using Broker.View.PolicyView;
using BrokerBase.Lib.Policy;
using BrokerBase.Lib.Person;
using Broker.View.CompanyView;
using Broker.Model;
using BrokerBase.Lib.Tool;
using NHibernate;
using BrokerBase.Lib.Product;

namespace Broker
{
    /// <summary>
    /// Interaction logic for MainForm.xaml
    /// </summary>
    public partial class MainForm
    {
        public MainForm()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(MainForm_Loaded);
        }

        void MainForm_Loaded(object sender, RoutedEventArgs e)
        {

            //AppGlobal.MainWin = this;

            AddOrDisplayTab(new HomePage2(), "欢迎");

            AppGlobal.DataWCF.ClientRegInfoChanged += new Update.ClientRegInfoChangedHandler(DataWCF_ClientRegInfoChanged);

            bool isSuccess = Login();

            ISession sess=AppGlobal.HbmSessionFactory.GetCurrentSession();

            if (isSuccess)
            {
                Broker.View.LibGlobal.MainWin = this;
                LoadInfo();
            }
            else
            {
                Close();
            }
        }

        void DataWCF_ClientRegInfoChanged(BrokerBase.Lib.Client.ClientDataInfo info)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                if (AppGlobal.ResultClientRegInfo.IsNewData)
                {
                    imgUpdate.Visibility = Visibility.Visible;
                }
                else
                {
                    imgUpdate.Visibility = Visibility.Hidden;
                }
            }));
        }

        private void lbiConfig_Selected(object sender, RoutedEventArgs e)
        {
            
        }

        private void AddOrDisplayTab(Page page, string title)
        {
            RadDocumentPane rdp = GetPane(title);

            if (rdp != null)
            {
                pgPlatform.SelectedItem = rdp;
            }
            else
            {
                Frame frame = new Frame();
                frame.Content = page;

                RadDocumentPane pane = new RadDocumentPane();
                
                pane.Tag = title;
                pane.Content = frame;
                pane.Header = title;
                
                pane.FontFamily = new FontFamily("宋体");
                pane.CanFloat = false;
                pgPlatform.Items.Add(pane);
            }

        }

        private RadDocumentPane GetPane(string tag)
        {
            RadDocumentPane rdp = null;

            foreach (object o in pgPlatform.Items)
            {
                RadDocumentPane dp = o as RadDocumentPane;

                if (dp.Tag != null && dp.Tag.ToString() == tag)
                {
                    rdp = dp;
                    break;
                }
            }

            return rdp;
        }


        private void lbiConfig_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            ConfigPage page = new ConfigPage();

            AddOrDisplayTab(page, "系统设置");
        }

        private void RadTreeViewItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            
        }

        private bool Login()
        {
            try
            {
                IList<SysUser> users = DBServiceUtil.GetService<SysUser>(AppGlobal.HbmSessionFactory.GetCurrentSession()).GetListByHQL("from SysUser").ToList<SysUser>();

                if (LicenseInfo.GetInstance().IsEffective)
                {
                    if (users.Count > 0 && AppGlobal.ClientCfg.IsLogin)
                    {
                        LoginForm frm = new LoginForm(users[0].Name);
                        frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                        frm.Owner = this;
                        frm.ResizeMode = ResizeMode.NoResize;
                        frm.ShowDialog();

                        return frm.IsSuccess;
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    RegPromptForm frm = new RegPromptForm(this);
                    frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                    frm.ResizeMode = ResizeMode.NoResize;
                    frm.ShowDialog();

                    return true;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        private void MenuButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string name = (sender as RadButton).Name;

                if (name == "btnFrist")
                {
                    HomePage2 page = new HomePage2();
                    AddOrDisplayTab(page, "欢迎");
                }
                else if (name == "btnCustomer")
                {
                    PersonListPage page = new PersonListPage();

                    AddOrDisplayTab(page, "客户管理");
                }
                else if (name == "btnProduct")
                {
                    ProductListPage page = new ProductListPage();

                    AddOrDisplayTab(page, "产品浏览");
                }
                else if (name == "btnRelation")
                {
                    PersonRelationMapPage page = new PersonRelationMapPage();
                    AddOrDisplayTab(page, "人际关系");
                }
                else if (name == "btnFast")
                {

                    IScheme scheme = new Scheme();
                    scheme.BizDate = DateTime.Now;
                    scheme.CreateDate = DateTime.Now;

                    SexType defaultSex=AppGlobal.ClientCfg.DefaultSex=="男"?SexType.Male:SexType.Fmale;

                    scheme.HolderSex = defaultSex;
                    scheme.HolderAge = PersonUtil.GetAgeFromBirthdayAndTime(AppGlobal.ClientCfg.DefaultBirthday, DateTime.Now);

                    scheme.InsurantSex = defaultSex;
                    scheme.InsurantAge = PersonUtil.GetAgeFromBirthdayAndTime(AppGlobal.ClientCfg.DefaultBirthday, DateTime.Now);

                    IPolicyLight pl = new PolicyLight(scheme, new Policy(scheme,ProductType.Basic));

                    scheme.PolicyLights.Add(pl);
                    
                    Scheme2Form frm = new Scheme2Form(scheme, SchemeType.Fast);

                    frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                    frm.Owner = AppGlobal.MainWin;
                    frm.Show();
                }
                else if (name == "btnScheme")
                {
                    SchemeListPage page = new SchemeListPage();
                    AddOrDisplayTab(page, "保单列表");
                }
                else if (name == "btnUpdate")
                {
                    UpdatePage page = new UpdatePage();

                    AddOrDisplayTab(page, "数据下载");
                }
                else if (name == "btnStatistics")
                {
                    HomePage page = new HomePage();
                    AddOrDisplayTab(page, "统计");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnHome_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(@"http://www.milliondone.com");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnSetting_Click(object sender, RoutedEventArgs e)
        {
            ConfigForm frm = new ConfigForm();
            frm.Owner = this;
            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            frm.ShowDialog();
        }

        private void btnRegister_Click(object sender, RoutedEventArgs e)
        {
            UserInfoForm frm = new UserInfoForm();
            frm.Owner = this;
            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;

            frm.ShowDialog();
        }

        private void LoadInfo()
        {
            try
            {
                if (AppGlobal.CurrentUser != null)
                {
                    string org = AppGlobal.CurrentUser.OrganizationName;
                    string user = AppGlobal.CurrentUser.Name;

                    tbkUser.Text = string.IsNullOrEmpty(org) ? user : org + "  " + user;
                }
                BrokerBase.Lib.Client.IEdition ed = EditionUtil.GetEditionByEnum((BrokerBase.Lib.Client.EditionType)LicenseInfo.GetInstance().MaxLicenseType);

                tbkVerson.Text = EditionUtil.GetEditionByEnum((BrokerBase.Lib.Client.EditionType)LicenseInfo.GetInstance().MaxLicenseType).Name;

                
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                AppGlobal.Log.Error(e.Message + Environment.NewLine + e.StackTrace);
            }
        }

        private void btnScoreInfo_Click(object sender, RoutedEventArgs e)
        {
            ScoreForm frm = new ScoreForm();
            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            frm.Owner = this;
            frm.ShowDialog();
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("是否退出美联达保险展业软件", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                this.Close();
            }
        }

        private void btnAbout_Click(object sender, RoutedEventArgs e)
        {
            AboutForm frm = new AboutForm();
            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            frm.Owner = this;
            frm.ShowDialog();
        }

        private void btnHelp_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(@"http://www.milliondone.com/product_summary.html");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
